import axio from "axios";
import { getStore, setStore, removeStore } from "./storage";
import router from "../router/index";
import { Message } from "element-ui";

//请求前的URL设定
let baseUrl = `${
  process.env.NODE_ENV === "production" ? "" : "proxyLS"
}/yl1001/platform/api`;
const axios = axio.create({
  withCredentails: true,
  timeout: 30000,
});
// 超时设定
axios.defaults.timeout = 15000;

axios.interceptors.request.use(
  (config) => {
    return config;
  },
  (err) => {
    Message.error("请求超时");
    return Promise.resolve(err);
  }
);

// http response 拦截器
axios.interceptors.response.use(
  (response) => {
    const data = response.data;
    // 根据返回的code值来做不同的处理(和后端约定)
    switch (data.code) {
      case 401:
        // 未登录 清除已登录状态
        removeStore("authorization");
        removeStore("userInfo");
        removeStore("AllPermissionList");
        removeStore("sideMenu");
        removeStore("roles");
        if (router.history.current.name != "login") {
          // if (data.status_desc !== null) {
          //     Message.error(data.status_desc);
          // } else {
          //     Message.error("登录已失效，请重新登录");
          // }
          router.push("/login");
        }
        break;
      case 403:
        // 没有权限
        if (data.status_desc !== null) {
          Message.error(data.status_desc);
        } else {
          Message.error("对不起没有权限操作!");
        }
        return;
      default:
        return data;
    }

    return data;
  },
  (err) => {
    // 返回状态码不为200时候的错误处理
    if (err.response) {
      let code = err.response.status;
      let data = err.response.data;
      switch (code) {
        case 401: //未验证通过
          removeStore("authorization");
          removeStore("userInfo");
          removeStore("AllPermissionList");
          removeStore("sideMenu");
          removeStore("roles");
          // if (data.status_desc !== null) {
          //     Message.error(data.status_desc);
          // } else {
          //     Message.error("登录已失效，请重新登录");
          // }
          router.push("/login");
          break;
        case 403:
          // 没有权限
          if (data.status_desc !== null) {
            Message.error(data.status_desc);
          } else {
            Message.error("对不起没有权限操作!");
          }
          return;
        default:
          return data;
      }
    }
    return Promise.resolve(err);
  }
);

export const getRequest = (url, params, proxy) => {
  let authorization = getStore("SaaStoken");
  let selfUrl = `${
    process.env.NODE_ENV === "production" ? "" : "proxyLS"
  }/yl1001/platform/api`;
  if (proxy && proxy == "proxyDp") {
    selfUrl = `${process.env.NODE_ENV === "production" ? "" : proxy}`;
  }
  return axios({
    method: "get",
    url: `${selfUrl}${url}`,
    params: params,
    headers: {
      Authorization: `${authorization}`,
    },
  });
};

export const postRequest = (url, params, proxy) => {
  let authorization = getStore("SaaStoken");
  let selfUrl = `${
    process.env.NODE_ENV === "production" ? "" : "proxyLS"
  }/yl1001/platform/api`;
  if (proxy && proxy == "proxyDp") {
    selfUrl = `${process.env.NODE_ENV === "production" ? "" : proxy}`;
  }
  return axios({
    method: "post",
    url: `${selfUrl}${url}`,
    data: params,
    transformRequest: [
      function (data) {
        let ret = "";
        for (let it in data) {
          ret +=
            encodeURIComponent(it) + "=" + encodeURIComponent(data[it]) + "&";
        }
        ret = ret.substring(0, ret.length - 1);
        return ret;
      },
    ],
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      Authorization: `${authorization}`,
    },
  });
};
export const postJsonRequest = (url, params, proxy) => {
  let authorization = getStore("SaaStoken");
  let selfUrl = `${
    process.env.NODE_ENV === "production" ? "" : "proxyLS"
  }/yl1001/platform/api`;
  if (proxy && proxy == "proxyDp") {
    selfUrl = `${process.env.NODE_ENV === "production" ? "" : proxy}`;
  }
  return axios({
    method: "post",
    url: `${selfUrl}${url}`,
    data: params,
    headers: {
      "Content-Type": "application/json;charset=UTF-8",
      Authorization: `${authorization}`,
    },
  });
};

export const putRequest = (url, params) => {
  let authorization = getStore("SaaStoken");
  return axios({
    method: "put",
    url: `${baseUrl}${url}`,
    data: params,
    transformRequest: [
      function (data) {
        let ret = "";
        for (let it in data) {
          ret +=
            encodeURIComponent(it) + "=" + encodeURIComponent(data[it]) + "&";
        }
        ret = ret.substring(0, ret.length - 1);
        return ret;
      },
    ],
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      Authorization: `${authorization}`,
    },
  });
};

export const deleteRequest = (url, params) => {
  let authorization = getStore("SaaStoken");
  return axios({
    method: "delete",
    url: `${baseUrl}${url}`,
    params: params,
    headers: {
      Authorization: `${authorization}`,
    },
  });
};

export const importRequest = (url, params) => {
  let authorization = getStore("SaaStoken");
  return axios({
    method: "post",
    url: `${baseUrl}${url}`,
    data: params,
    headers: {
      Authorization: `${authorization}`,
    },
  });
};

export const uploadFileRequest = (url, params) => {
  let authorization = getStore("SaaStoken");
  return axios({
    method: "post",
    url: `${baseUrl}${url}`,
    params: params,
    headers: {
      Authorization: `${authorization}`,
    },
  });
};

/**
 * Authorization
 * 无需登录认证的请求
 */
export const oauthTokenLogin = (url, params) => {
  return axios({
    method: "post",
    url: `${baseUrl}${url}`,
    params: params,
  });
};

/**
 * 无需token验证的请求 避免旧token过期导致请求失败
 * @param {*} url
 * @param {*} params
 */
export const getRequestWithNoToken = (url, params) => {
  return axios({
    method: "get",
    url: `${baseUrl}${url}`,
    params: params,
  });
};
export const adornUrl = (url, who) => {
  console.log(baseUrl);
  return `${baseUrl}${url}`;
};
